package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.FormDetailAdapter;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.FormDetail;
import com.isunland.managesystem.entity.FormDetailOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.Task;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 对象功能: 除待办外其他的表单详情,待办为ToDoFormDetailFragment.由于待办处理逻辑复杂,单独独立为一个类.避免代码过于复杂.
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2016/12/7 10:16
 */

public class FormDetailFragment extends Fragment {

  private static final String EXTRA_TASK =
      "com.isunland.managesystem.ui.FormDetailFragment.EXTRA_TASK";
  private static final int REQUEST_OPERATION = 1;
  public String menu_id = "";// 用于区别已办,请求.办结.
  private ListView mListView;
  private BaseVolleyActivity mActivity;
  private Task mTask;
  private String mTaskId;
  private FormDetailAdapter mAdapter;
  private FormDetailOriginal mFormDetailOriginal;
  private Button mBtnChild;
  private String mRunId;

  public static FormDetailFragment newInstance(Task mtaskContent) {
    Bundle args = new Bundle();

    args.putSerializable(EXTRA_TASK, mtaskContent);
    FormDetailFragment fragment = new FormDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    mTask = (Task) getArguments().getSerializable(EXTRA_TASK);
    if (mTask == null) return;
    mTaskId = mTask.getMyTaksId();
    menu_id = mTask.getmMenuId() + "";
    mRunId = mTask.getRunId();
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_form_detail, container, false);
    setUpViews(v);

    volleyPostInit();
    return v;
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    if ("1".equals(menu_id)) {
      inflater.inflate(R.menu.menu_already_done, menu);
    } else if ("2".equals(menu_id)) {
      inflater.inflate(R.menu.menu_my_request, menu);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    Intent i;
    if ("1".equals(menu_id)) {
      switch (item.getItemId()) {
        case android.R.id.home:

          if (NavUtils.getParentActivityName(getActivity()) != null) {
            NavUtils.navigateUpFromSameTask(getActivity());
          }

          return true;
        // 追回
        case R.id.menu_item_recover:
          i = new Intent(getActivity(), RecoverTaskActivity.class);
          i.putExtra(RecoverTaskFragment.EXTRA_TASK_ID, mTaskId);
          startActivityForResult(i, REQUEST_OPERATION);

          return true;
        // 催办
        case R.id.menu_item_reminders:
          i = new Intent(getActivity(), RemindersTaskActivity.class);
          i.putExtra(RemindersTaskFragment.EXTRA_ACT_ID, mTask.getActInstId());
          i.putExtra(RemindersTaskFragment.EXTRA_SUBJECT, mTask.getSubject());
          startActivityForResult(i, REQUEST_OPERATION);
          return true;
        default:
          break;
      }
    } else if ("2".equals(menu_id)) {
      switch (item.getItemId()) {
        case android.R.id.home:

          getActivity().finish();

          return true;
        // 追回
        case R.id.menu_item_recover:
          i = new Intent(getActivity(), RecoverTaskActivity.class);
          i.putExtra(RecoverTaskFragment.EXTRA_TASK_ID, mTaskId);
          startActivityForResult(i, REQUEST_OPERATION);

          return true;
        // 催办
        case R.id.menu_item_reminders:
          i = new Intent(getActivity(), RemindersTaskActivity.class);
          i.putExtra(RemindersTaskFragment.EXTRA_ACT_ID, mTask.getActInstId());
          i.putExtra(RemindersTaskFragment.EXTRA_SUBJECT, mTask.getSubject());
          startActivityForResult(i, REQUEST_OPERATION);
          return true;
        // 终止流程
        case R.id.menu_item_cancel:

          volleyPostStop();

          return true;
        default:
          return super.onOptionsItemSelected(item);
      }
    } else {
      switch (item.getItemId()) {
        case android.R.id.home:

          getActivity().finish();

          return true;
        default:
          return super.onOptionsItemSelected(item);
      }
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    switch (requestCode) {
      case REQUEST_OPERATION:
        getActivity().setResult(Activity.RESULT_OK);
        getActivity().finish();
        break;

      default:
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  private void volleyPostInit() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_FORM_INFO);
    ParamsNotEmpty params = new ParamsNotEmpty();

    params.put("runId", mTaskId);

    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        mFormDetailOriginal = new Gson().fromJson(arg0, FormDetailOriginal.class);

        ArrayList<FormDetail> formDetails = mFormDetailOriginal.getDataList();
        //循环遍历，已有借款合计name中包含mSumBorrowName，就更新对应value值
        for (int i = 0; i < formDetails.size(); i++) {
          //String name=formDetails.get(i).getName();
          String isHidden = formDetails.get(i).getIsHidden();//false：字段显示在界面上，true:隐藏
          if ("true".equalsIgnoreCase(isHidden)) {
            formDetails.remove(i);
            i--;
          }
        }
        getAdapter(formDetails);
        mAdapter.notifyDataSetChanged();

        if (mFormDetailOriginal.getDetailList() == null
            || mFormDetailOriginal.getDetailList().size() == 0) {
          mListView.removeFooterView(mBtnChild);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  private void setUpViews(View v) {
    mListView = (ListView) v.findViewById(R.id.lv_container);

    mBtnChild = new Button(getActivity());
    mBtnChild.setText(R.string.checkDetail);
    mBtnChild.setTextColor(Color.WHITE);
    mBtnChild.setBackgroundResource(R.drawable.selector_buttonshape);

    mBtnChild.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View v) {
        Intent intent = new Intent(getActivity(), FormChildLIstActivity.class);
        intent.putExtra(FormChildListFragment.EXTRA_CHILD_LIST,
            mFormDetailOriginal.getDetailList());
        startActivity(intent);
      }
    });
    mListView.addFooterView(mBtnChild);
  }

  private void getAdapter(ArrayList<FormDetail> formDetails) {
    if (mAdapter == null) {
      mAdapter = new FormDetailAdapter(getActivity(), formDetails);
      mListView.setAdapter(mAdapter);
    }
  }

  // 终止流程
  private void volleyPostStop() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    HashMap<String, String> params = new HashMap<>();
    params.put("runId", mRunId);
    LogUtil.i("终止流程params====" + params.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        LogUtil.i("终止流程====" + arg0);
        try {
          MyUtils.dismissDialog();
          // 解析
          SuccessMessage result = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == result || null == result.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = result.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(result.getMessage());
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            ToastUtil.show(R.string.success_operation);

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          ToastUtil.show(R.string.wrong_data);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }
    });
  }
}
